package com.xdja.utils;

/**
 * Created by wxq
 * on 2020/8/4
 */
public class TestWxq {

    public static void main(String[] args) {
        int[] numbs = {-4, 1, 2, 2, 5, 5, 5, 8, 10};
        int target = 20;
        //获取小于或者等于target的下标
        System.out.println(getNumberIndex(numbs, target));
    }

    private static int getNumberIndex(int[] numbs, int target) {
        if (numbs.length <= 0) {
            return -1;
        }
        int left = 0;//从小到大
        int right = numbs.length; //从大到小
        while (left <= right) {
            int middle = (left + right) / 2;
            if (numbs[middle] <= target) {
                //如果下一个索引值大于要寻找的值，则当前索引就是最小的
                //为避免数组越界，增加长度的限制，如果是最后一位，则直接返回
                if (middle == numbs.length-1 || numbs[middle+1] > target){
                    return middle;
                }else {
                    left = middle + 1;
                }
            } else if (numbs[middle] > target) {
                right = middle - 1;
            }
        }
        return -1;
    }
}